<?php
/**
 * Created by PhpStorm.
 * User: 4399-0661
 * Date: 15-5-9
 * Time: 下午2:14
 */

namespace Library\database;

class LibPdo extends LibBase
{
    public $column = 0;
    public $laseSql = "";

    /**
     * 连接
     * @return bool
     */
    public function connection()
    {
        $config = \LibConfig::readDB($this->key);
        if (!$config['HOST'] || !$config['DB_NAME'] || !$config['PASSWORD']) {
            $this->_halt("PDO connect mysql data exist NULl");
            return array();
        }
        $dsn = "mysql:host={$config['HOST']};";
        if ($config['PORT']) {
            $dsn .= "port={$config['PORT']};";
        }
        $dsn .= "dbname={$config['DB_NAME']};";
        if (!$config['CHARSET']) {
            $config['CHARSET'] = 'utf-8';
        }
        $dsn .= "charset={$config['CHARSET']}";
        try {
            $this->link = new \PDO($dsn, $config['USERNAME'], $config['PASSWORD']);
            $this->link->exec("set names {$config['CHARSET']}");
        } catch (\PDOException $e) {
            $this->_halt("PDO Connect Error:" . $e->getMessage());
        }
    }

    /**
     * 执行SQL
     * @param $sql
     * @return array|bool
     */
    public function query($sql)
    {
        if (!$this->link) {
            return $this->_halt("Mysql connection Error:");
        }
        $this->res = $this->link->query($sql);
        if (!$this->res) {
            return $this->_halt("Mysql query Error:" . $this->res->errorCode() . ":" . $this->res->errorInfo());
        }
        $this->count++;
    }

    /**
     * 查询结果集的处理
     */
    public function fetchResult($parmaryKey)
    {
        $datas = array();
        while ($row = $this->res->fetch(\PDO::FETCH_ASSOC)) {
            if ($parmaryKey && $row[$parmaryKey]) {
                $datas[$parmaryKey] = $row;
                continue;
            }
            $datas[] = $row;
        }
        return $datas;
    }

    /**
     * 开始事务
     */
    public function translateStart()
    {
        $this->link->beginTransaction();
    }

    /**
     * 提交事务
     */
    public function translateCommit()
    {
        $this->link->commit();
    }

    /**
     * 事务回滚
     */
    public function translateRollBack()
    {
        $this->link->rollBack();
    }

    /**
     * 释放资源
     */
    public function close()
    {
        $this->link = null;
    }

    /**
     * 返回最后一个插入中自动生成的 ID
     * @return int|string
     */
    public function getInsertId()
    {
        return $this->link->lastInsertId();
    }

    /**
     * 返回前一次SQL操作所影响的记录行数。
     * @return int
     */
    public function getAffectedRows()
    {
        return $this->res->rowCount();
    }

    /**
     * 获得上一次连接错误的提示
     * @return array
     */
    public function getAfterError()
    {
        return [
            "errno" => $this->res->errorCode(),
            "error" => $this->res->errorInfo()
        ];
    }
} 